<!--
 * @Description: 巡检计划管理页面
-->
<template>
  <BaseMainSlot>
    <template v-slot:btn-box>
      <ActionBar
        :page-no="76"
        :add-active="addActive"
        :del-active="delActive"
        :edit-active="editActive"
        :cancel-active="cancelActive"
        :save-active="saveActive"
        :has-edit="false"
        :has-save="false"
        @add="add"
        @cancel="cancel"
        @edit="edit"
        @del="del"
        @save="save('formData')"
      />
    </template>
    <template v-slot:search-box>
      <SearchForm :formConfig="formConfig" :formData="searchlist" @search="search"></SearchForm>
    </template>
    <template v-slot:table-box>
      <el-table
        ref="tableData"
        v-loading="loading"
        :data="tableData"
        stripe
        border
        height="calc(100% - 50px)"
        @row-click="handleEdit"
        @selection-change="handleSelectionChange"
      >
        <!-- @current-change="handleCurrentChange" -->
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="inspectionPlanName" label="巡查计划名称" min-width="120" />
        <!-- <el-table-column prop="inspectionRouteName" label="巡查线路" /> -->
        <el-table-column label="执行频率">
          <template v-if="scope.row.inspectionPlanId" slot-scope="scope">
            <div v-if="scope.row.dayRate || scope.row.monthRate || scope.row.hourRate">
              <div v-if="scope.row.dayRate">{{ scope.row.dayRate + '天' }}</div>
              <div v-if="scope.row.hourRate">{{ scope.row.hourRate + '时' }}</div>
              <div v-if="scope.row.monthRate">{{ scope.row.monthRate + '月' }}</div>
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="employeeName" label="巡查人" /> -->
        <el-table-column prop="endTime" label="计划状态">
          <template v-if="scope.row.inspectionPlanId" slot-scope="scope">
            <div
              :style="rowendTime(scope.row.endTime) === '已过期' ? 'color:red' : ''"
            >{{ rowendTime(scope.row.endTime) }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template v-if="scope.row.inspectionPlanId" slot-scope="scope">
            <el-button
              v-if="judgePermission(76, 'edit')"
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="edit"
            >
              <i class="el-icon-edit-outline"></i> 修改
            </el-button>
            <el-button
              v-if="judgePermission(76, 'delete')"
              class="text-btn-cursor cursor-delete"
              type="text"
              size="small"
              @click="handleDelete(scope.row)"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <el-dialog
        :title="dialogTitle + '巡查计划信息'"
        :visible.sync="dialogFormVisible"
        :before-close="cancel"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item label="巡查计划名称:" prop="inspectionPlanName" class="w100p">
            <el-input v-model="formData.inspectionPlanName" placeholder="请输入巡查计划名称" clearable />
          </el-form-item>
          <el-form-item label="计划执行频率:" prop="val" class="w100p val">
            <el-form-item prop="monthRate">
              <el-select v-model="formData.monthRate" filterable clearable @change="monthRate">
                <el-option v-for="(item, index) in 12" :key="index" :value="item" />
              </el-select>
              <div class="Rate">月</div>
            </el-form-item>
            <el-form-item prop="dayRate">
              <el-select v-model="formData.dayRate" filterable clearable @change="dayRate">
                <el-option v-for="(item, index) in 31" :key="index" :value="item" />
              </el-select>
              <div class="Rate">天</div>
            </el-form-item>
            <el-form-item prop="hourRate">
              <el-select v-model="formData.hourRate" filterable clearable @change="hourRate">
                <el-option v-for="(item, index) in 24" :key="index" :value="item" />
              </el-select>
              <div class="Rate">时</div>
            </el-form-item>
          </el-form-item>
          <el-form-item label="计划有效时间:" class="w100p val">
            <el-form-item prop="startTime" class="w50p">
              <el-tooltip
                class="item"
                effect="dark"
                content="计划开始时间必须大于当前时间"
                placement="bottom-end"
              >
                <el-date-picker
                  v-model="formData.startTime"
                  :picker-options="startDatePicker"
                  type="datetime"
                  placeholder="计划开始日期"
                  value-format="timestamp"
                />
              </el-tooltip>
            </el-form-item>
            <div class="sort-box">~</div>
            <el-form-item prop="endTime" class="w50p">
              <el-date-picker
                v-model="formData.endTime"
                :picker-options="endDatePicker"
                type="datetime"
                placeholder="计划结束日期"
                value-format="timestamp"
              />
            </el-form-item>
          </el-form-item>
          <el-form-item label="计划启停:" prop="inspectionOnOff" class="w100p elRadio">
            <el-switch v-model="inspectionOnOff" />
          </el-form-item>
        </el-form>
        <el-form
          ref="inspectionRouteId"
          label-position="left"
          :model="addformData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item label="任务名称:" prop class="w50p">
            <el-input v-model="addformData.inspectionTaskName" clearable />
          </el-form-item>
          <el-form-item label="巡查线路:" prop class="w50p">
            <el-select
              v-model="addformData.inspectionRouteId"
              clearable
              filterable
              @change="changenowPointId"
            >
              <el-option
                v-for="item in patrolLine"
                :key="item.inspectionRouteId"
                :label="item.inspectionRouteName"
                :value="item.inspectionRouteId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="巡查人:" prop="address" class="w50p">
            <el-select v-model="addformData.employeeName" clearable filterable>
              <el-option
                v-for="item in staffData"
                :key="item.person.personNo"
                :label="item.person.name"
                :value="item.person.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="任务生成时间:" prop="birthday" class="w50p">
            <el-tooltip class="item" effect="dark" content="任务生成时间必须大于当前时间" placement="bottom">
              <el-date-picker
                v-model="addformData.generateTime"
                type="datetime"
                placeholder="请输入任务生成时间"
                clearable
                :picker-options="endate"
                value-format="timestamp"
              />
            </el-tooltip>
          </el-form-item>
        </el-form>
        <div class="pointList">
          <div class="label-input">
            <div class="label">添加任务:</div>
            <div class="input">
              <i
                class="el-icon-circle-plus-outline"
                :class="canInput ? '' : 'noClick'"
                @click="addPoint()"
              ></i>
            </div>
          </div>
          <div class="tags">
            <div
              v-for="(items, index) in tagsList"
              :key="index"
              class="tag-item"
              @click="seeTheTag(items)"
            >
              <div class="point-name">{{ items.inspectionTaskName }}</div>
              <div class="close">
                <i class="el-icon-circle-close" @click.stop="removeTheTag(index)"></i>
              </div>
            </div>
          </div>
        </div>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button class="zh-button-two" type="primary" @click="save('formData')">保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import SearchForm from '@/components/searchForm';
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import patrolInfoManage from "@/api/digital-operation/patrol-info-manage/patrol-line-manage";
import InspectionPlan from "@/api/digital-operation/patrol-info-manage/patrol-plan-manage";
import staffManage from "@/api/digital-operation/personnel-cost-mansge/staff-manage";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot.vue";
import { mymixin } from "@/utils/mixins";
import { mapGetters } from "vuex";

export default {
  name: "PatrolPlanManage",
  components: {
    SearchForm,
    ActionBar,
    Pagination,
    BaseMainSlot,
  },
  mixins: [mymixin],
  data() {
    return {
      formConfig: [
        {
          label: '巡查计划名称',
          prop: 'inspectionPlanName',
          type: 'input',
        },
      ],
      searchlist: {},
      userName: "",
      // 选中的数据项数组 employeeId组成 (此数组最多为一个)
      selectedStaffList: [],
      patrolLine: [],
      inspectionPlanName: "",
      staffData: [],
      addformData: {},
      formData: {},
      tagsList: [],
      inspectionOnOff: "true",
      startDatePicker: this.beginDate(),
      endDatePicker: this.processDate(),
      endate: this.endates(),
      rules: {
        inspectionPlanName: [
          { required: true, message: "请输入巡查计划名称", trigger: "blur" }
        ],
        val: [
          { required: true, message: "请选择任意一个执行频率", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "请选择开始时间", trigger: "change" }
        ],
        endTime: [
          { required: true, message: "请选择结束时间", trigger: "change" }
        ]
      },
      dialogTitle: "",
      dialogFormVisible: false
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {
    formData: {
      handler(val) {
        if (val.monthRate) {
          this.formData.val = val.monthRate;
        }
        if (val.dayRate) {
          this.formData.val = val.dayRate;
        }
        if (val.hourRate) {
          this.formData.val = val.hourRate;
        }
      }
    }
  },
  created() {
    this.getstaffManageList();
    // let that = this;
    // that.getdatatime();
  },
  mounted() {
    //  查询表格数据
    this.search();
  },
  methods: {
    //  查询表格数据
    getTableDataList() {
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        order: "asc",
        entity: {
          inspectionPlanName: this.searchlist.inspectionPlanName || undefined,
          organizationNo: sessionStorage.organizationNo
        }
        // supplierId: this.supplierId
      };
      InspectionPlan.getInspectionPlanList(params).then(res => {
        this.loading = false;
        let data = res.data;
        if (data) {
          this.totalSize = data.totalElements;
          this.tableData = data.content;
          this.addblankmet();
          this.resetActionBar();
        }
      });
    },
    async getstaffManageList() {
      const { data: res } = await staffManage.getStaffListByCondition();
      this.staffData = res;
      const { data: resp } = await patrolInfoManage.inspectionRouteCondition();
      this.patrolLine = resp;
    },
    rowendTime(e) {
      let endTime = new Date().getTime();
      // let expireTime = (new Date()).getTime() - 1 * 24 * 60 * 60 * 1000
      if (endTime > e) {
        return "已过期";
      } else if (endTime < e) {
        return "未过期";
      }
    },
    // 限制前面日期不能低于后面日期
    beginDate() {
      const self = this;
      return {
        disabledDate(time) {
          if (self.formData.endTime) {
            //  如果结束时间不为空，则小于结束时间
            return new Date(self.formData.endTime).getTime() < time.getTime();
          } else {
            // return time.getTime() > Date.now()// 开始时间不选时，结束时间最大值小于等于当天
          }
        }
      };
    },
    processDate() {
      const self = this;
      // if (self.endTime) {
      return {
        disabledDate(time) {
          if (self.formData.startTime) {
            //  如果开始时间不为空，则结束时间大于开始时间
            self.time = new Date();
            return new Date(self.formData.startTime).getTime() > time.getTime();
          } else {
            // return time.getTime() > Date.now() // 开始时间不选时，结束时间最大值小于等于当天
          }
        }
      };
    },
    endates() {
      const self = this;
      // if (self.endTime) {
      return {
        disabledDate(time) {
          if (self.addformData.generateTime) {
            self.time = new Date();
            return time.getTime() < Date.now() - 1 * 24 * 60 * 60 * 1000;
            // return new Date(self.addformData.generateTime).getTime() < time.getTime();
          } else {
            self.time = new Date();
            return time.getTime() < Date.now() - 1 * 24 * 60 * 60 * 1000;
            // return new Date(self.addformData.generateTime).getTime() < time.getTime();
          }
        }
      };
    },
    changenowPointId(val) {
      this.nowPointId = val;
      this.patrolLine.forEach(item => {
        if (item.inspectionRouteId === val) {
          this.addformData.inspectionRouteName = item.inspectionRouteName;
        }
      });
    },
    // 新增任务
    addPoint() {
      if (!this.canInput) {
        return;
      } else {
        this.patrolLine.forEach(item => {
          if (item.inspectionRouteId === this.addformData.inspectionRouteId) {
            this.addformData.inspectionRouteName = item.inspectionRouteName;
          }
        });
        let arr = [];
        arr.push(this.addformData);
        // console.log(this.addformData)
        if (arr.length > 0) {
          if (!this.formData.val) {
            this.$message.warning("请选择计划执行频率！");
            return;
          }
          if (!this.addformData.inspectionRouteId) {
            this.$message.warning("请选择巡查路线！");
            return;
          }
        }
        if (this.tagsList.length > 0) {
          let idList = [];
          idList = this.tagsList.map(item => item.inspectionTaskName);
          if (idList.includes(arr[0].inspectionTaskName)) {
            this.$message.warning("该任务已经存在~");
            return;
          } else {
            if (!this.addformData.inspectionTaskName) {
              this.$message.warning("任务名称不能为空~");
              return;
            }
            this.tagsList = JSON.parse(
              JSON.stringify(this.tagsList.concat(arr))
            );
          }
          this.addformData = {};
        } else {
          if (!this.addformData.inspectionTaskName) {
            this.$message.warning("任务名称不能为空~");
            return;
          }
          this.tagsList = JSON.parse(JSON.stringify(this.tagsList.concat(arr)));
          this.addformData = {};
          return;
        }
      }
    },
    removeTheTag(pointId) {
      if (this.canInput) {
        this.tagsList.forEach((item, index) => {
          if (index === pointId) {
            this.tagsList.splice(index, 1);
          }
        });
      } else {
        this.$message.warning("点击修改按钮后可删除~");
      }
    },
    seeTheTag(e) {
      if (this.addformData.inspectionTaskName !== e.inspectionTaskName) {
        this.addformData = e;
        return;
      }
      if (this.addformData.inspectionTaskName) {
        this.addformData = {};
      } else {
        this.addformData = e;
      }
    },
    monthRate(val) {
      this.formData.val = val;
      if (val) {
        delete this.formData.dayRate;
        delete this.formData.hourRate;
      }
    },
    dayRate(val) {
      this.formData.val = val;
      if (val) {
        delete this.formData.monthRate;
        delete this.formData.hourRate;
      }
    },
    hourRate(val) {
      this.formData.val = val;
      if (val) {
        delete this.formData.monthRate;
        delete this.formData.dayRate;
      }
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    // add() {
    //   this.canInput = true;
    //   this.formData = {};
    //   this.openDialog('add');
    // },
    handleEdit(row) {
      // TODO 点击行元素后 edit
      // 点击行清空上一步数据
      this.tagsList = [];
      this.formData = JSON.parse(JSON.stringify(row));
      this.inspectionOnOff = this.formData.inspectionOnOff;
      // console.log(this.inspectionOnOff)
      delete this.formData.deleteFlagName;
      // console.log(this.formData)
      if (row.inspectionPlanId) {
        InspectionPlan.queryInspectionPlan(row.inspectionPlanId).then(res => {
          // console.log(res)
          let data = res.data;
          this.tagsList = data.inspectionTaskList;
        });
      }
      // this.tagsList = this.formData.inspectionTaskList
      // this.addActive = false;
      this.editActive = true;
      this.saveActive = false;
      this.cancelActive = true;
      // this.$refs.formData.resetFields();
      // this.canInput = false;
      // this.openDialog('edit');
    },
    handleSelectionChange(list) {
      this.inspectionPlanIdList = [];
      this.inspectionPlanIdList = list.map(item => item.inspectionPlanId);
      if (this.inspectionPlanIdList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage() {
      InspectionPlan.delInspectionPlaniInfo(this.inspectionPlanIdList).then(
        res => {
          if (res.code === 1) {
            this.$message.success(res.msg);
            this.$refs.formData.resetFields();
            this.search();
            this.resetActionBar();
          } else {
            this.$message.warning(res.msg || "删除失败");
          }
        }
      );
    },
    handleDelete(data) {
      // InspectionPlan.delInspectionPlaniInfo([data.inspectionPlanId]).then(
      //   (res) => {
      //     if (res.code === 1) {
      //       this.$message.success(res.msg);
      //       // this.$refs.formData.resetFields();
      //       this.search();
      //       this.resetActionBar();
      //     } else {
      //       this.$message.warning(res.msg || '删除失败');
      //     }
      //   }
      // );
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          InspectionPlan.delInspectionPlaniInfo([data.inspectionPlanId]).then(
            res => {
              if (res.code === 1) {
                this.$message.success(res.msg);
                this.search();
                this.resetActionBar();
              } else {
                this.$message.warning(res.msg || "删除失败");
              }
            }
          );
        })
        .catch(() => {
          this.$message("取消删除");
        });
    },
    cancel(formData) {
      this.deleteFlag = true;
      this.nowChanceStau = "";
      this.formData = {};
      this.tagsList = [];
      this.addformData = {};
      this.inspectionOnOff = false;
      this.canInput = false;
      this.addActive = true;
      this.delActive = false;
      this.saveActive = false;
      this.cancelActive = false;
      this.editActive = false;
      this.closeDialog();
      if (formData) {
        this.$refs[formData].resetFields();
      }
      this.$refs.tableData.setCurrentRow();
    },
    save(formData) {
      // console.log(this.formData)
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            this.formData.inspectionTaskList = this.tagsList;
            this.formData.inspectionOnOff = this.inspectionOnOff;
            delete this.formData.val;
            InspectionPlan.editInspectionPlaniInfo(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "修改成功！");
                this.closeDialog();
                this.$refs[formData].resetFields();
                this.search();
              } else {
                this.$message.error(res.msg || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            this.formData.inspectionOnOff = this.inspectionOnOff;

            this.formData.inspectionTaskList = this.tagsList;
            // if(this.formData.inspectionTaskList) {
            //   this.$message.warning('新建计划，任务')
            // }
            // console.log(this.formData)
            // return
            delete this.formData.val;
            InspectionPlan.addInspectionPlaniInfo(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "新增成功！");
                this.closeDialog();
                this.$refs[formData].resetFields();
                this.search();
              } else {
                this.$message.error(res.msg || "新增失败！");
              }
            });
          }
        } else {
          // console.log('error submit!!');
          return false;
        }
      });
    },
    openDialog(type) {
      this.dialogFormVisible = true;
      this.dialogTitle = type === "add" ? "新增" : "编辑";
      this.nowChanceStau = type;
    },
    closeDialog() {
      this.dialogFormVisible = false;
      this.dialogTitle = null;
      this.nowChanceStau = "";
    }
  }
};
</script>

<style lang="scss" scoped>
@import "~@/styles/variables.scss";
::v-deep .el-form-item__content {
  display: flex;
  align-items: center;
}
::v-deep .el-input__inner {
  background-color: transparent;
  color: #fff;
  // border-radius: 5px;
  border-color: #6ecae3;
}
.label {
  min-width: 100px;
}
::v-deep .el-form-item__label {
  min-width: 120px !important;
  text-align: end !important;
  font-size: 10px;
}
.el-form-item {
  margin-bottom: 20px;
}
//   ::v-deep .el-input__prefix{
//     position: absolute;
//   }
.el-radio {
  height: 33px;
  line-height: 33px;
  color: #fff;
}
.sort-box {
  display: inline-block;
  // width: 2px;
  width: 31px;
  text-align: center;
  // transform: rotateY(90deg);
  // .sort {
  //   padding: 0 5px;
  //   transform: rotate(-90deg);
  // }
}
.el-switch {
  margin-top: 8px;
}
.staff-manage {
  .common-layout {
    .content {
      .form {
        // overflow-y: initial;
        justify-content: flex-start;
      }
    }
  }
}
.elRadio {
  border-bottom: 1px dashed #6ecae3;
}

.pointList {
  .label-input {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
    .label {
      min-width: 80px !important;
      text-align: end;
      height: 30px;
      font-size: 10px;
      line-height: 30px;
      padding-right: 5px;
    }
  }
  i {
    font-size: 30px;
    margin-left: 10px;
    cursor: pointer;
  }
  .noClick {
    cursor: not-allowed;
  }
  .df {
    display: flex;
    align-items: center;
    width: 100%;
  }
  ::v-deep .el-form-item__content {
    flex-direction: column;
  }
  .label {
    min-width: 100px !important;
  }
  .tags {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    .tag-item {
      height: 30px;
      padding: 5px 10px;
      background-color: #00a1c2;
      border-radius: 8px;
      display: flex;
      align-items: center;
      margin-top: 10px;
      margin-right: 10px;
      i {
        font-size: 14px;
      }
    }
  }
}
.Rate {
  padding: 0 20px;
}
.val {
  ::v-deep .el-form-item {
    margin: 0 !important;
    .el-form-item__content {
      flex-wrap: nowrap !important;
    }
  }
}
</style>
